﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;
using ShopOnline.BLL;
using System.Web.Services;
using ShopOnline.Controls;

namespace ShopOnline
{
    public partial class BusinessCard : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ((GeneralMaster)this.Master).SetPageTitle("Business Card");
            
            lblNoCards.Visible = View_Customers.GetCurrentUser() == null || View_Customers.GetCurrentUser().RowCount <= 0;
            adminPanel.Visible = View_Users.GetCurrentUser() != null && View_Users.GetCurrentUser().RowCount > 0;
            lstMyCards.Visible = View_Customers.GetCurrentUser() != null && View_Customers.GetCurrentUser().RowCount > 0;
            lstTemplates.ReadOnly = View_Users.GetCurrentUser() == null || View_Users.GetCurrentUser().RowCount == 0;
            lstMyCards.ReadOnly = View_Customers.GetCurrentUser() == null || View_Customers.GetCurrentUser().RowCount == 0;
            int index = 0;
            if (!IsPostBack)
            {
                CardPapers paper = CardPapers.GetActivePapers();
                POSSystem.BLL.Utilities.LoadDropDownListNoSelectNoSort(ddlPapers, paper.DefaultView, CardPapers.ColumnNames.Name, CardPapers.ColumnNames.ID);
                PaperPrices prices = PaperPrices.GetPrices(paper.ID, 100);
                if (prices.RowCount > 0)
                    litPrice.Text = string.Format("{0:C}", prices.UnitPrice);
                lstTemplates.Rebind();
                lstMyCards.Rebind();

                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    int id = int.Parse(Request.QueryString["id"]);
                    BusinessCards bc = new BusinessCards();
                    bc.LoadByPrimaryKey(id);
                    if (bc.RowCount > 0)
                    {
                        hidBack.Value = bc.s_BackSide;
                        hidFront.Value = bc.s_FrontSide;
                        index = 1;
                    }
                }
            }

            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "initBusinessCard(" + index.ToString() + ");", true);
        }

        protected void lstTemplates_OnNeedDataSource(object sender, EventArgs e)
        {
            BusinessCards bc = new BusinessCards();
            int count = bc.Search(string.Format("{0} = 0 and {1} = {2}", BusinessCards.ColumnNames.Deleted, BusinessCards.ColumnNames.Status, BusinessCardStatus.Template), string.Format("{0} desc", BusinessCards.ColumnNames.ID), dataPagerTemplates.CurrentPageIndex * dataPagerTemplates.PageSize, dataPagerTemplates.PageSize);
            dataPagerTemplates.TotalItems = count;

            lstTemplates.DataSource = bc.DefaultView;
            string js = "$('#" + lstTemplates.ClientID + " .bcObject').draggable({ containment: 'parent', start: function () { $('.bcselected').removeClass('bcselected'); $(this).addClass('bcselected'); } });";
            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), js, true);
        }

        protected void dataPagerTemplates_OnPageIndexChanged(object sender, PageIndexChangedEventArgs e)
        {
            lstTemplates.Rebind();
        }

        protected void lstMyCards_OnNeedDataSource(object sender, EventArgs e)
        {
            if (View_Customers.GetCurrentUser() != null && View_Customers.GetCurrentUser().RowCount > 0)
            {
                BusinessCards bc = new BusinessCards();
                int count = bc.Search(string.Format("{0} = 0 and {1} = {2}", BusinessCards.ColumnNames.Deleted, BusinessCards.ColumnNames.CreatedByCustomer, View_Customers.GetCurrentUser().ID), string.Format("{0} desc", BusinessCards.ColumnNames.ID), dataPagerTemplates.CurrentPageIndex * dataPagerTemplates.PageSize, dataPagerTemplates.PageSize);
                dataPagerMine.TotalItems = count;

                lstMyCards.DataSource = bc.DefaultView;

                string js = "$('#" + lstMyCards.ClientID + " .bcObject').draggable({ containment: 'parent', start: function () { $('.bcselected').removeClass('bcselected'); $(this).addClass('bcselected'); } });";
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), js, true);
            }
        }

        protected void dataPagerMine_OnPageIndexChanged(object sender, PageIndexChangedEventArgs e)
        {
            lstMyCards.Rebind();
        }

        [WebMethod]
        public static string GetPrice(int paperID, int quantity)
        {
            PaperPrices prices = PaperPrices.GetPrices(paperID, quantity);
            if (prices.RowCount > 0)
                return string.Format("{0:C}", prices.UnitPrice);
            return "N/A";
        }

        [WebMethod]
        public static string LoadCardContent(int id)
        {
            BusinessCards bc = new BusinessCards();
            bc.LoadByPrimaryKey(id);

            return bc.s_FrontSide;
        }

        protected void btnAddToCart_OnClick(object sender, EventArgs e)
        {
            BusinessCards SelectedBCs = new BusinessCards();
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                int id = int.Parse(Request.QueryString["id"]);
                SelectedBCs.LoadByPrimaryKey(id);
            }
            else
            {
                SelectedBCs.AddNew();
                SelectedBCs.ID = -SelectedBCs.RowCount;
                SelectedBCs.CreatedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                SelectedBCs.Deleted = false;
                SelectedBCs.Status = BusinessCardStatus.Draft;
            }

            SelectedBCs.FrontSide = hidFront.Value;
            SelectedBCs.BackSide = hidBack.Value;
            SelectedBCs.Save();

            string price = hidPrice.Value.Replace("$", "");
            OrderItems items = BasePage.SelectedItems;
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                int id = int.Parse(Request.QueryString["id"]);
                items.Filter = OrderItems.ColumnNames.ProductID + "=" + id.ToString();
                if (items.RowCount == 0)
                {
                    items.Filter = "";
                    items.AddNew();
                    if (!items.DefaultView.Table.Columns.Contains(BasePage.PRODUCT_IMAGE))
                        items.AddColumn(BasePage.PRODUCT_IMAGE, typeof(string));
                    items.Deleted = false;
                    items.ID = -items.RowCount;
                }
            }
            else
            {
                items.AddNew();
                if (!items.DefaultView.Table.Columns.Contains(BasePage.PRODUCT_IMAGE))
                    items.AddColumn(BasePage.PRODUCT_IMAGE, typeof(string));
                items.Deleted = false;
                items.ID = -items.RowCount;
            }
            
            items.ProductID = SelectedBCs.ID;
            items.ProductName = txtName.Text == "" ? "Business Card" : txtName.Text;
            items.Name = items.ProductName;
            items.s_Quantity = txtQuantity.Text;
            items.s_CustomerPrice = price;
            items.s_UnitCost = "0";
            items.s_UnitPrice = price;
            items.s_UnitDealerPrice = price;
            items.TotalAmount = items.Quantity * items.CustomerPrice;
            items.GST = Math.Round(items.TotalAmount * SystemVariables.SysVars.GST / (SystemVariables.SysVars.GST + 100), 2);
            
            items.BarCode = "";
            items.s_ProductImage ="";
            items.Category = OrderItemCategory.BusinessCard;
            if (items.s_ProductImage != "")
            {
                ProductImages img = ProductImages.GetById(int.Parse(items.s_ProductImage));
                if (img.RowCount > 0)
                    items.SetColumn(BasePage.PRODUCT_IMAGE, ShopOnline.Utilities.GetImageUrl(img.s_ThumbUrl));
            }
            else
                items.SetColumn(BasePage.PRODUCT_IMAGE, GetDefaultPic());

            items.Filter = "";

            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showNotification('All For You Online', 'Your Shopping Cart has been updated!', 8000);", 1), true);
        }

        public string GetDefaultPic()
        {
            return this.ResolveUrl("~/images/cardcopy.png");
        }

        protected void btnSaveTemplate_OnClick(object sender, EventArgs e)
        {
            BusinessCards SelectedBCs = new BusinessCards();
            SelectedBCs.AddNew();
            SelectedBCs.ID = -SelectedBCs.RowCount;
            SelectedBCs.FrontSide = hidFront.Value;
            SelectedBCs.BackSide = hidBack.Value;
            SelectedBCs.CreatedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
            SelectedBCs.Deleted = false;
            SelectedBCs.Status = BusinessCardStatus.Template;
            SelectedBCs.Save();

            lstTemplates.Rebind();

            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showNotification('All For You Online', 'Save successfully!', 8000);", 1), true);
        }
    }
}